/**
 * @param {string} s
 * @return {boolean}
 */

// 简单解法
var isValid = function (s) {
  const n = s.length;
  if (n % 2 !== 0) {
    return false;
  }
  const news = s.replace(/{}|\[\]|\(\)|/g, '');
  if (news.length !== n) {
    return isValid(news);
  } else if (news.length === 0) {
    return true;
  } else {
    return false;
  }
};

// 优化解法。使用栈的数据结构
var isValid = function (s) {
  const n = s.length;
  if (n % 2 === 1) {
    return false;
  }
  const pairs = new Map([
    [')', '('],
    [']', '['],
    ['}', '{']
  ]);
  const stk = [];
  for (let ch of s) {
    if (pairs.has(ch)) {
      if (!stk.length || stk[stk.length - 1] !== pairs.get(ch)) {
        return false;
      }
      stk.pop();
    }
    else {
      stk.push(ch);
    }
  };
  return !stk.length;
};

console.log(isValid('()[]{}([)]'));